//
//  HomeViewController.m
//  Weibo
//
//  Created by taoshanchang on 15/1/21.
//  Copyright (c) 2015年 taoshanchang. All rights reserved.
//

#import "HomeViewController.h"
#import "WeiboSDK.h"
#import "WBHttpRequest.h"
#import "MainViewController.h"
#import "ThemeManager.h"
#import "CONSTS.h"
#import "WeiboModel.h"
#import "UIFaactory.h"
#import "UIViewExt.h"
#import "MainViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "DetailViewController.h"
#import "AppDelegate.h"



@interface HomeViewController ()

@end

@implementation HomeViewController


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if(self){
        self.title = @"微博";
        
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //开启左滑、又滑菜单
    [self.appDelegate.menuController setEnableGesture:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //关闭左滑、又滑菜单
    [self.appDelegate.menuController setEnableGesture:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //绑定按钮
    UIBarButtonItem *bindItem = [[UIBarButtonItem alloc] initWithTitle:@"绑定账户" style:UIBarButtonItemStylePlain target:self action:@selector(bindAction:)];
    [bindItem setTintColor:[[ThemeManager sharedInstance] getColorWithName:kThemeListLabel]];
    self.navigationItem.rightBarButtonItem = bindItem;
    //注销按钮
    UIBarButtonItem *lgoutItem = [[UIBarButtonItem alloc] initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(lgoutAction:)];
    [lgoutItem setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = lgoutItem;
    //微博列表
    _tableView = [[WeiboTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-20-49-44) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.eventDelegate = self;
    
    _tableView.hidden = YES;
    
    //判断是否登录验证
     NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"SinaWeiboAuthData"][@"accessTokenKey"];
    if(accessToken != nil){
        [self loadWeiboData];
    }else{
        [self login];
    }
}

#pragma - mark UI
-(void) showNewWeiboCount:(long)count{
    if(_barView ==nil){
        _barView = [UIFaactory createImageView:@"timeline_new_status_background"];
        UIImage *image = [_barView.image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
        _barView.image = image;
        _barView.leftCapWidth = 5;
        _barView.topCapHeight = 5;
        _barView.frame = CGRectMake(5, -40, ScreenWidth-10, 40);
        [self.view addSubview:_barView];
        
        UILabel *label= [[UILabel alloc] initWithFrame:CGRectZero];
        label.tag = 2015;
        label.font = [UIFont systemFontOfSize:16.0f];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        [_barView addSubview:label];
    }
    
    if(count > 0 ){
        UILabel *label = (UILabel *)[_barView viewWithTag:2015];
        label.text = [NSString stringWithFormat:@"%ld条新微博",count];
        [label sizeToFit];
        label.origin = CGPointMake((_barView.width-label.width)/2, (_barView.height-label.height)/2);
        [UIView animateWithDuration:0.6 animations:^{
            _barView.top = 5;
        } completion:^(BOOL finished) {
            if(finished){
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDelay:1];
                [UIView setAnimationDuration:.6];
                _barView.top = -40 ;
                [UIView commitAnimations];
            }
        }];
        
        //播放系统提示音
        NSString *path = [[NSBundle mainBundle] pathForResource:@"msgcome" ofType:@"wav"];
        NSURL *url = [NSURL fileURLWithPath:path];
        
        SystemSoundID soundId;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundId);
        AudioServicesPlaySystemSound(soundId);
    }
    //隐藏未读图标
    MainViewController *mainViewController = (MainViewController *)self.tabBarController;
    [mainViewController showBadge:YES];
}

#pragma mark - load Data

-(void)loadWeiboData{

    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"SinaWeiboAuthData"][@"accessTokenKey"];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"18" forKey:@"count"];
    [WBHttpRequest requestWithAccessToken:accessToken url:@"https://api.weibo.com/2/statuses/friends_timeline.json" httpMethod:@"GET" params:params delegate:self withTag:@"loadData"];
    self.tableView.isMore = YES;
}

-(void)pullDownData{
    if(self.topWeiboId.length == 0){
        NSLog(@"微博ID为空");
        return ;
    }
    [self showHUD];
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"SinaWeiboAuthData"][@"accessTokenKey"];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"8", @"count", self.topWeiboId, @"since_id", nil];
    [WBHttpRequest requestWithAccessToken:accessToken url:@"https://api.weibo.com/2/statuses/friends_timeline.json" httpMethod:@"GET" params:params queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        [self pullDownDataFinished:result];
    }];

}

-(void)pullDownDataFinished:(id)result{
    //隐藏进度条
    [super hideHUD];
    [super showHUDComplete:@""];
    //显示tableView
    _tableView.hidden = NO;
    
    
    NSArray *statues = [result objectForKey:@"statuses"];
    NSMutableArray *newWeibos = [NSMutableArray arrayWithCapacity:statues.count];
    for (NSDictionary *statuesDic in statues) {
        WeiboModel *weibo = [[WeiboModel alloc] initWithDataDic:statuesDic];
        [newWeibos addObject:weibo];
    }
    
    if(newWeibos.count > 0){
    
        WeiboModel *temp = [newWeibos objectAtIndex:0];
        self.topWeiboId = [temp.weiboId stringValue];
    }

    [newWeibos addObjectsFromArray:self.weibos];
    self.weibos = newWeibos;
    self.tableView.data = newWeibos;
    //刷新ui
    [self.tableView reloadData];
    //下拉回弹
    [self.tableView doneLoadingTableViewData];
    ;
    
    NSLog(@"下拉更新条数:%lu",[statues count]);
    
    [self showNewWeiboCount:[statues count]];
    
}

-(void)pullupData{
    if(self.lastWeiboId.length == 0){
        NSLog(@"微博ID为空");
        return ;
    }
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"SinaWeiboAuthData"][@"accessTokenKey"];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"8", @"count", self.lastWeiboId, @"max_id",accessToken ,@"access_token" , nil];
    [WBHttpRequest requestWithAccessToken:accessToken url:@"https://api.weibo.com/2/statuses/friends_timeline.json" httpMethod:@"GET" params:params queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        [self pullUpDataFinished:result];
    }];

}

-(void)pullUpDataFinished:(id)result{
    
    
    NSArray *statues = [result objectForKey:@"statuses"];
    NSMutableArray *newWeibos = [NSMutableArray arrayWithCapacity:statues.count];
    for (NSDictionary *statuesDic in statues) {
        WeiboModel *weibo = [[WeiboModel alloc] initWithDataDic:statuesDic];
        [newWeibos addObject:weibo];
    }
    
    
    //更新lastId
    if(newWeibos.count > 0){
        [newWeibos removeObjectAtIndex:0];//移除重复的一条
        WeiboModel *temp = [newWeibos lastObject];
        self.lastWeiboId = [temp.weiboId stringValue];
    }
    //判断是不是又更多，上面我一次取8条这里判断是不是有大于8条
    if(newWeibos.count >= 8){
        self.tableView.isMore = YES;
    }else{
        self.tableView.isMore = NO;
    }
    
    [self.weibos addObjectsFromArray:newWeibos];
    
    self.tableView.data = self.weibos;
    [self.tableView reloadData];
    
}

-(void)refreshWeibo{
    //使UI下拉
    [self.tableView refreshData];
    self.tableView.hidden = NO;
    //加载数据
    [self pullDownData];
}

#pragma mark - action

-(void)bindAction:(UIBarButtonItem *)buttonItem{
    [self login];
}

-(void)login{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"HomeViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}

-(void)lgoutAction:(UIBarButtonItem *)lgoutItem {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

#pragma mark - weibo delegate

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"网络加载失败：%@",error);
}


- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result{
    //隐藏进度条
    [super hideHUD];
    [super showHUDComplete:@""];
    //显示tableView
    _tableView.hidden = NO;
    
    NSError *error;
    NSData *dataContent = [result dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultData = [NSJSONSerialization JSONObjectWithData:dataContent options:NSJSONReadingMutableLeaves error:&error];
    NSArray *statues = [resultData objectForKey:@"statuses"];
    NSMutableArray *weiboArray = [NSMutableArray arrayWithCapacity:statues.count];
    for (NSDictionary *statuesDic in statues) {
        WeiboModel *weibo = [[WeiboModel alloc] initWithDataDic:statuesDic];
        [weiboArray addObject:weibo];
    }
    self.tableView.data = weiboArray;
    self.weibos = weiboArray;
    //取出微博的第一条id和最后一条Id
    if(weiboArray.count > 0){
        WeiboModel *topWeibo = [weiboArray objectAtIndex:0];
        self.topWeiboId = [topWeibo.weiboId stringValue];
        
        WeiboModel *lastWeibo = [weiboArray lastObject];
        self.lastWeiboId = [lastWeibo.weiboId stringValue];
    }
    [self.tableView reloadData];
}

#pragma - mark tableViewEventDelegate
//下拉
-(void)pullDown:(BaseTableView *)tableView{
    [self pullDownData];
}

//上拉
-(void)pullUp:(BaseTableView *)tableView{
    [self pullupData];
}
//选中一个cell

-(void)tableView:(BaseTableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"select cell");
    WeiboModel *weibo = [self.weibos  objectAtIndex:indexPath.row];
    DetailViewController *detailViewController = [[DetailViewController alloc] init];
    detailViewController.weiboModel = weibo;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
                              
                              

#pragma mark - memory Manager
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
